import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bloc/bloc.dart';
import './risk_unit_event.dart';
import './risk_unit_state.dart';
import 'package:safety_platform/repository/risk.dart';
import 'package:safety_platform/models/risk_unit.dart';
class RiskUnitListBloc extends Bloc<RiskUnitEvent, RiskUnitListState> {
  RiskUnitListState get initialState => RiskUnitListState([]);

  RiskRepository _repository = RiskRepository();
  @override
  Stream<RiskUnitListState> mapEventToState(
      RiskUnitListState currentState, RiskUnitEvent event) async* {
    if (event is RiskUnitRefreshEvent) {
      if (event.throwLoadingState) {
        //TODO
      }
      List<RiskUnit> results  = await _repository.getAllRiskUnit();

      if (results!=null && results.isNotEmpty) {
          yield RiskUnitListState(results);
      }
    }
  }
}



class RiskUnitBloc extends Bloc<RiskUnitDetailEvent, RiskUnitDetailState> {

  RiskUnitDetailState inital;
  RiskUnitBloc({this.inital});
  RiskRepository _repository = RiskRepository();

  @override
  RiskUnitDetailState get initialState => this.inital?? EmptyRiskUnitDetailState();


  Stream<RiskUnitDetailState> _loadRiskUnit(int riskUnitid) async * {
       RiskUnit riskUnit = await _repository.getUnitFromCache(riskUnitid.toString());
       yield RiskUnitDetailState(riskUnit);

    }

  @override
  Stream<RiskUnitDetailState> mapEventToState(RiskUnitDetailState currentState, 
  RiskUnitDetailEvent event) async* {
    if (event is RiskUnitStartupEvent) {

      RiskUnit riskUnit =event.riskUnit;

      String unitId;
      if (riskUnit != null) {
        if (riskUnit.risks == null) {
          yield LoadingRiskUnitRiskState(riskUnit);
          unitId =riskUnit.id.toString();
        } else {
          yield RiskUnitDetailState(riskUnit);
        }
      } else {
        yield LoadingRiskUnitDetailState(null);
        unitId = event.riskUnitId;
      }
      if (unitId != null) {
        riskUnit = await _repository.getUnitFromCache(unitId);
        if (riskUnit != null) {
          yield RiskUnitDetailState(riskUnit);
        }
        riskUnit =  await _repository.getRiskUnit(unitId);
        yield RiskUnitDetailState(riskUnit);

      }

    }
   }
}